package ch8;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Random;

public class TraceHandler implements InvocationHandler {
    private static int count;
    private Object target;
    public TraceHandler(Object t){
        target = t;
        count = 0;
    }

    public static int getCount() {
        return count;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        count++;
        System.out.print(target);
        System.out.print("."+ method.getName()+"(");
        if(args!=null){
            for (int i = 0; i < args.length; i++) {
                System.out.print(args[i]);
                if (i<args.length - 1) {
                    System.out.print(", ");
                }
            }
        }
        System.out.println(")");
        return method.invoke(target,args);
    }

    public static void main(String[] args) {
        Object[] elements = new Object[1000];
        for (int i=0;i<elements.length;i++){
            Integer value = i + 1;
            InvocationHandler handler = new TraceHandler(value);
            Class[] interfaces = new Class[]{Comparable.class};
            elements[i] = Proxy.newProxyInstance(null,interfaces,handler);
            //判断elements[i]是否是代理类
//            System.out.println(Proxy.isProxyClass(elements[i].getClass()));
        }

        Integer key = new Random().nextInt(elements.length) + 1;
        int result = Arrays.binarySearch(elements,key);
        if(result >= 0){
            System.out.println(elements[result]);
        }
        System.out.println(count);
        assert count < 0;

    }
}
